package com.attilax.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import aaaCfg.IocX;

import com.attilax.core;
import com.attilax.jsonX;
import com.attilax.db.DBX;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.lang.Trigger;
import com.attilax.lang.YamlAtiX;
import com.attilax.lang.xml.XmlX;
//import com.attilax.db.DbX;
import com.attilax.net.requestImp;
import com.google.inject.Inject;

/**
 * req2easyui fmt json aaaCfg.IocX com.attilax.api.ApiSqlHandler
 * 
 * @author Administrator
 *
 */
public class ApiSqlHandler {
	public Map mp = new ConcurrentHashMap<String, Handler>();

	public ApiSqlHandler() {

		this.reg("sql", new Handler() {

			@Override
			public Object handleReq(Object arg) throws Exception {
				// attilax 老哇的爪子 l_43_u o87

				List li = dbx.findBySql(arg.toString());

				return core.toJsonStrO88(li);

			}
		});
		

		this.reg("auth-url_outer", new Handler() {

			@Override
			public Object handleReq(Object arg) throws Exception {
				// attilax 老哇的爪子 l_43_u o87

				HttpServletRequest req = (HttpServletRequest) arg;

				String auth_code_frm_client = req.getParameter("auth_code");

				String authCodeServer = filex.read(
						pathx.webAppPath() + "/code_hq.txt").trim();
				if (auth_code_frm_client.trim().equals(authCodeServer))
					return "t";
				else
					return "f";

			}
		});
	}

	public void reg(String subMeth, Handler handler) {
		mp.put(subMeth, handler);

	}

	@Inject
	DBX dbx;

	public static void main(String[] args) {

		ApiSqlHandler ax = IocX.getBean(ApiSqlHandler.class);
		requestImp ri = new requestImp();
		// ri.setParam("http_param", "select 1");
		ri.setParam("http_param", "select * from gv_material limit 0,10");
		ri.setParam("ret_datatype", "xml");

		// &=xml
		System.out.println(ax.handleReq(ri));

	}
	public Trigger trigger;
	
	@SuppressWarnings("rawtypes")
	public String handleReq(final HttpServletRequest req) {
		if(req.getParameter("method")!=null)
			return handleReq_dsl(req);
		System.out.println("--");
		try {
			String sql = req.getParameter("http_param");
			if (sql == null)
				throw new RuntimeException("http_param is null 缺少参数");
			// DbX dx = aaaCfg.IocX.getBean(DbX.class);
			List<Map> li = new ArrayList<Map>(); // update
			int count = 0;
			if (sql.trim().toLowerCase().startsWith("select")) {
				li = dbx.findBySql(sql);
				if(trigger!=null)
					trigger.exec(li);
				count = dbx.getCount(sql.toString());
			} else {
				li = dbx.execSql(sql);
				count = (Integer) li.get(0).get("num");
			}
			Map easyuiFmtRzt = easyuiFmtRzt(li, count);
			if (req.getParameter("ret_datatype") != null
					&& req.getParameter("ret_datatype").equals("xml")) {
				// @SuppressWarnings("rawtypes")
				slashPath(li);
//				if(trigger!=null)
//					trigger.exec(li);
				List li2 = convert2anothFmt(li);
				String xml2 = XmlX.toXml2(li2, "data", "item");
				return xml2;
			}
			// def json
			return core.toJsonStrO88(easyuiFmtRzt);
		} catch (Exception e) {
			return core.toJsonStrO88(e);
		}

		// return
	}

	private String handleReq_dsl(HttpServletRequest req) {
		String meth=req.getParameter("method");
		Handler hd=(Handler) mp.get(meth);
		try {
			return (String) hd.handleReq(req);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return meth;
	}

	@SuppressWarnings("all")
	private void slashPath(List<Map> li) {
		for (int i = 0; i < li.size(); i++) {
			try {
				Map m = li.get(i);
				String path = (String) m.get("file_path");
				String path2 = pathx.convertSlashPath(path);
				m.put("file_path", path2);
			} catch (Exception e) {
				e.printStackTrace();
			}
			;
		}
	}

	private List convert2anothFmt(List li) {
		String f = pathx.webAppPath() + "/0cfg/video2xmlMapTxt.txt";
		Map mpr = YamlAtiX.getMap(f);
		List li2 = new ArrayList();
		for (int i = 0; i < li.size(); i++) {
			Object object = li.get(i);

			Map m_ori = (Map) object;
			TreeMap m = new TreeMap();
			m.putAll(m_ori);
			m.put("test", "aa");

			Map m2 = new TreeMap();
			m2.putAll(m);
			Set<Entry<String, Object>> enSet = mpr.entrySet();
			// for(int j=0;j<enSet.size();j++)

			for (Entry<String, Object> entry : enSet) {
				String newKey = entry.getKey();// tiele
				String old_key = entry.getValue().toString();
				// if(newKey!=null)
				m.put(newKey, m.get(old_key));
			}
			li2.add(m);
		}
		return li2;
	}

	/**
	 * @author attilax 老哇的爪子
	 * @since p32 l_9_f
	 */
	protected Map easyuiFmtRzt(List li, int count) {
		Map m = new HashMap();
		m.put("rows", li);
		m.put("total", count);
		return m;
	}
}
